<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/05/05
 */
namespace api\modules\v1\controllers\boat;

use common\logic\Boat;
use common\logic\Occupancy;
use common\logic\Order;
use common\logic\Trip;
use common\models\Cabin;
use common\models\OrderForm;
use common\tool\Alarm;
use Faker\Provider\bg_BG\PhoneNumber;
use libphonenumber\PhoneNumberUtil;
use yii\web\Controller;
use Yii;
use yii\web\Response;

class OrderController extends Controller {
    public $enableCsrfValidation = false;

    public function beforeAction($action) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return parent::beforeAction($action);
    }

    public function actionCreate() {
        if (Yii::$app->user->isGuest) {
            return [
                'code' => 403,
                'msg' => '未登录'
            ];
        }
        $post = Yii::$app->request->post();

        $model = new OrderForm();
        $model->load($post, '');
        $model->validate();
        if ($model->hasErrors()) {
            return [
                'err' => 1,
                'msg' => current($model->getFirstErrors())
            ];
        }
//        $isValid = true;
//        try {
//            $phoneUtil = PhoneNumberUtil::getInstance();
//            $swissNumberProto = $phoneUtil->parse($post['phone']);
//            $isValid = $phoneUtil->isValidNumber($swissNumberProto);
//        } catch (\libphonenumber\NumberParseException $e) {
//        }
//        if(!$isValid){
//            return [
//                'err' => 1,
//                'msg' => '手机号格式错误',
//            ];
//        }

        $data = $model->getAttributes();
        $r = Order::createOrder($data['contact'],$data['name'], $data['email'], $data['phone'], $data['useFund']??0, $data['useProtect']??'',
            $data['rental']??[], $data['message']??'', $data['tripId'], $data['cabinId'], $data['oneself'], $data['course']??'');
        if ($r['err'] == 0) {
            Yii::$app->redis->lpush(Yii::$app->params['redisKey']['createOrderQueue'], $r['orderId']);
            return [
                'code' => 200,
                'data' => [
                    'orderId' => $r['orderId'],
                    'price' => $r['price'],
                ]
            ];
        } else {
            return [
                'code' => 401,
                'msg' => $r['msg'],
            ];
        }
    }
}
